#import "BarcodeScannerViewController.h"
//#import "QRCodeScannerView.h"
#import <LanYouToolBox/QRCodeScannerView.h>

@interface BarcodeScannerViewController ()

@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic, strong) UIView *scanRectView;
@property (nonatomic, strong) UILabel *resultLabel;

@property (nonatomic, strong) QRCodeScannerView *scannerView;

@end

@implementation BarcodeScannerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
//    self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    
    [self setupUI];
//    [self checkCameraPermission];
    
    // 初始化扫描视图
    [self setupScannerView];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.previewLayer.frame = self.view.bounds;
    [self setupScanRect];
}

- (void)setupScannerView {
    self.scannerView = [[QRCodeScannerView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.scannerView];
    
//    [self.scannerView startScanAnimation];
}

#pragma mark - UI Setup

- (void)setupUI {
    // 初始化结果标签
    self.resultLabel = [[UILabel alloc] init];
    self.resultLabel.textColor = [UIColor whiteColor];
    self.resultLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
    self.resultLabel.textAlignment = NSTextAlignmentCenter;
    self.resultLabel.numberOfLines = 0;
    self.resultLabel.font = [UIFont systemFontOfSize:16];
    self.resultLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.resultLabel];
    
    // 初始化扫描框
    self.scanRectView = [[UIView alloc] init];
    self.scanRectView.layer.borderColor = [UIColor greenColor].CGColor;
    self.scanRectView.layer.borderWidth = 2;
    self.scanRectView.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:self.scanRectView];
    
    // 添加约束
    [NSLayoutConstraint activateConstraints:@[
        [self.resultLabel.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:-20],
        [self.resultLabel.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:20],
        [self.resultLabel.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-20]
    ]];
}

- (void)setupScanRect {
    // 设置扫描框大小为屏幕中间的正方形区域
    CGFloat scanSize = MIN(self.view.bounds.size.width, self.view.bounds.size.height) * 0.7;
    CGRect scanFrame = CGRectMake(
        (self.view.bounds.size.width - scanSize) / 2,
        (self.view.bounds.size.height - scanSize) / 2,
        scanSize,
        scanSize
    );
    self.scanRectView.frame = scanFrame;
}

#pragma mark - Camera Setup

- (void)checkCameraPermission {
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                [self setupCaptureSession];
            } else {
                [self showCameraPermissionDeniedAlert];
            }
        });
    }];
}

- (void)setupCaptureSession {
    self.captureSession = [[AVCaptureSession alloc] init];
    
    // 配置输入设备
    AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
    
    if (input && [self.captureSession canAddInput:input]) {
        [self.captureSession addInput:input];
        
        // 配置元数据输出
        AVCaptureMetadataOutput *metadataOutput = [[AVCaptureMetadataOutput alloc] init];
        
        if ([self.captureSession canAddOutput:metadataOutput]) {
            [self.captureSession addOutput:metadataOutput];
            
            // 设置代理和队列
            [metadataOutput setMetadataObjectsDelegate:self queue:dispatch_queue_create("com.barcode.scanner", DISPATCH_QUEUE_SERIAL)];
            
            // 配置支持的条码类型（主流码制）
            metadataOutput.metadataObjectTypes = @[
                AVMetadataObjectTypeQRCode,               // QR码
                AVMetadataObjectTypeDataMatrixCode,       // Data Matrix
                AVMetadataObjectTypePDF417Code,           // PDF417
                AVMetadataObjectTypeCode128Code,          // Code 128
                AVMetadataObjectTypeEAN13Code,            // EAN-13
                AVMetadataObjectTypeEAN8Code,             // EAN-8
                AVMetadataObjectTypeCode39Code,           // Code 39
                AVMetadataObjectTypeAztecCode             // Aztec
            ];
            
            // 设置扫描区域（基于设备坐标）
            [self setupScanRegion:metadataOutput];
            
            // 配置预览层
            [self setupPreviewLayer];
            
            // 启动会话
            [self.captureSession startRunning];
        } else {
            [self showErrorWithMessage:@"无法添加元数据输出"];
        }
    } else {
        [self showErrorWithMessage:error.localizedDescription ?: @"无法访问摄像头"];
    }
    
    [self.scannerView startScanAnimation];
}

- (void)setupPreviewLayer {
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.previewLayer.frame = self.view.bounds;
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];
}

- (void)setupScanRegion:(AVCaptureMetadataOutput *)output {
    // 将扫描框坐标转换为AVFoundation的坐标系统（原点在右上角，取值范围0-1）
    CGRect scanRect = self.scanRectView.frame;
    CGFloat x = scanRect.origin.y / self.view.bounds.size.height;
    CGFloat y = scanRect.origin.x / self.view.bounds.size.width;
    CGFloat width = scanRect.size.height / self.view.bounds.size.height;
    CGFloat height = scanRect.size.width / self.view.bounds.size.width;
    
    output.rectOfInterest = CGRectMake(x, y, width, height);
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate

- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject;
        
        // 停止扫描以避免重复识别
        [self.captureSession stopRunning];
        
        // 在主线程更新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *result = [NSString stringWithFormat:@"类型: %@\n内容: %@", 
                               [self barcodeTypeName:metadataObject.type], 
                               metadataObject.stringValue];
            self.resultLabel.text = result;
            
            // 3秒后重新开始扫描
            [self performSelector:@selector(resumeScanning) withObject:nil afterDelay:3.0];
        });
    }
}

- (void)resumeScanning {
    if (!self.captureSession.isRunning) {
        [self.captureSession startRunning];
        self.resultLabel.text = @"对准条码进行扫描...";
    }
}

#pragma mark - Helper Methods

- (NSString *)barcodeTypeName:(NSString *)type {
    NSDictionary *typeNames = @{
        AVMetadataObjectTypeQRCode: @"QR Code",
        AVMetadataObjectTypeDataMatrixCode: @"Data Matrix",
        AVMetadataObjectTypePDF417Code: @"PDF417",
        AVMetadataObjectTypeCode128Code: @"Code 128",
        AVMetadataObjectTypeEAN13Code: @"EAN-13",
        AVMetadataObjectTypeEAN8Code: @"EAN-8",
        AVMetadataObjectTypeCode39Code: @"Code 39",
        AVMetadataObjectTypeAztecCode: @"Aztec"
    };
    
    return typeNames[type] ?: type;
}

- (void)showCameraPermissionDeniedAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"权限不足" 
                                                                   message:@"请在设置中允许应用访问摄像头以使用扫描功能" 
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showErrorWithMessage:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" 
                                                                   message:message 
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

@end
    
